import Head from 'next/head'
import { Pagination } from '../../components'
import { toRelativeTime, transformId } from '../../utils'
import { dataService } from '../../services'
import { ICategory } from '../../typings'
import styles from '../../styles/list.module.css'

export default function List({ items, page, category, parentCategory }: IListModel) {

  return (
    <div className="main-container">
      <Head>
        <title>{category.name} - {process.env.siteName}</title>
      </Head>
      {
        parentCategory && (
          <div className={styles.categorys}>
            {parentCategory.children && parentCategory.children.map((n) => (
              <a key={n.id} className={n.path === category.path ? styles.current : ''} href={`/list/${n.path}`}>{n.name}</a>
            ))}
          </div>
        )
      }
      <div className={styles.list}>
        {
          items.map((item) => (
            <div key={item.id} className={styles['item-box']}>
              <div className={styles.cover}>
                <img className="cover" src={`/api/cover/${item.id}`} />
              </div>
              <div className={styles.infos}>
                <div className={styles.title}>
                  <a href={`/detail/${item.id}`} target="_blank" rel="noreferrer">{item.title}</a>
                </div>
                <div className={styles.time} title={item.date}>更新时间：{item.relativeTime}</div>
                <div className={styles.brief}>{item.brief}</div>
              </div>
            </div>
          ))
        }
      </div>
      <script src="/js/cover.js"></script>
      <div className={styles.pagination}>
        <Pagination current={page.current} total={page.total * 25} pageSize={25} />
      </div>
    </div>
  )
}

export async function getServerSideProps(props: any) {
  let path = Array.isArray(props.query.all) ? props.query.all.join('/') : ''
  let page = parseInt(props.query.page)
  if (isNaN(page) || page < 1) {
    page = 1
  }
  let { category, parent = null } = dataService.getCategoryByPath(path)
  if (!category) {
    throw new Error('404')
  }
  let $ = (await dataService.getListDoc(category, page))!
  if (!$) {
    throw new Error('404')
  }
  let model = {
    items: [],
    category: category,
    page: {
      current: page
    }
  } as unknown as IListModel
  $('.co_content8 table').each<any>(function () {
    let item = {} as IListItem
    let $a = $(this).find('a').last()
    item.id = transformId($a.attr('href')?.replace('/html/', '')!)
    item.title = $a.text()
    let dateExec = /(\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d)/.exec($(this).find('tbody tr:nth-child(3) font').text())
    if (dateExec && dateExec.length > 0) {
      item.date = dateExec[0]
      item.relativeTime = toRelativeTime(item.date)
    } else {
      item.date = item.relativeTime = '未知'
    }

    item.brief = $(this).find('tbody tr:nth-child(4)').text().trim()
    model.items.push(item)
  })
  model.page.total = parseInt($('.co_content8 .x option').last().text())
  model.parentCategory = parent

  return { props: model }
}

interface IListModel {
  items: IListItem[]
  page: IPageInfo
  category: ICategory
  parentCategory?: ICategory | null
}
interface IPageInfo {
  current: number
  total: number
}
interface IListItem {
  id: string
  title: string
  date: string
  relativeTime: string
  brief: string
}